package arithmetic.LeetCode.Degree_of_an_Array;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * @author zhangyanqi
 * @since 1.0 2017/10/16
 */
public class Solution2 {

    public int findShortestSubArray(int[] nums) {

        List<Integer> list = new LinkedList<>();

        int length = nums.length;
        int[] mark = new int[50000];
        for (int i = 0; i < length; i++) {
            mark[nums[i]]++;
        }
        int maxCount = 0;
        for (int i = 0; i < mark.length; i++) {
            if (mark[i] > maxCount) {
                list.clear();
                maxCount = mark[i];
                list.add(i);
            } else if (mark[i] == maxCount) {
                list.add(i);
            }
        }
        Iterator<Integer> iterator = list.iterator();
        int min = 0;
        while (iterator.hasNext()) {
            Integer mun = iterator.next();
            int begin = 0;
            for (int i = 0; i < length; i++) {
                if (nums[i] == mun) {
                    begin = i;
                    break;
                }
            }
            int end = 0;
            for (int i = length - 1; i > 0; i--) {
                if (nums[i] == mun) {
                    end = i;
                    break;
                }
            }
            int i = end - begin;
            if (i <= min || min == 0) {
                min = i;
            }
        }
        return min + 1;
    }


    public static void main(String[] args) {
        Solution2 s = new Solution2();
        int[] i = {1, 2, 3, 5, 2};
        int shortestSubArray = s.findShortestSubArray(i);
        System.out.println(shortestSubArray);
    }
}

